/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-14     GC       the first version
 */
#include "ble.h"
#include "string.h"
#include "rfid.h"
#define SAMPLE_UART_NAME       "uart2"




/* 用于接收消息的信号量 */
struct rt_semaphore rx_sem1;



rt_thread_t ble_thread;

rt_device_t ble;



/* 接收数据回调函数 */
static rt_err_t uart2_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到数据后产生中断，调用此回调函数，然后发送接收信号量 */
    rt_sem_release(&rx_sem1);

    return RT_EOK;
}


static void serial_rx_entry(void *parameter)
{
    char ch;

    while (1)
    {
        //中断函数接收数据部分
        /* 从串口读取一个字节的数据，没有读取到则等待接收信号量 */
        while (rt_device_read(ble, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信号量，等到信号量后再次读取数据 */
            rt_sem_take(&rx_sem1, RT_WAITING_FOREVER);
        }
        //rt_kprintf("%c",ch);
        if(ch=='O')
        {
            rt_kprintf("%c",ch);
            ch='0';
            door_flag = 1;
        }
        else if (ch=='N') {
            rt_kprintf("%c",ch);
            ch='0';
            door_flag = 0;
        }
        rt_thread_mdelay(100);
    }
}

/*
函数功能：uart线程
函数形参：void
函数返回值：void
函数说明：线程优先级为  5  时间片为10
*/
int ble_init(void)
{
    rt_err_t ret1 = RT_EOK;
    char uart2_name[RT_NAME_MAX];
    rt_strncpy(uart2_name, SAMPLE_UART_NAME, RT_NAME_MAX);
    /* 查找系统中的串口设备 ，查找串口1*/
    ble = rt_device_find(uart2_name);
    if (!ble)
    {
        rt_kprintf("find %s failed!\n", uart2_name);
        return RT_ERROR;
    }

    /*初始化信号量 */
    rt_sem_init(&rx_sem1, "rx_sem1", 0, RT_IPC_FLAG_FIFO);
    /* 以中断接收及轮询发送模式打开串口设备 */
    rt_device_open(ble, RT_DEVICE_FLAG_INT_RX);
    /* 设置接收回调函数 */
    rt_device_set_rx_indicate(ble, uart2_input);

    /* 创建 serial 线程 */
    ble_thread = rt_thread_create("ble", serial_rx_entry, RT_NULL, 512, 5, 10);
    /* 创建成功则启动线程 */
    if (ble_thread != RT_NULL)
    {
        rt_kprintf("uart2 rx success.\n");
        rt_thread_startup(ble_thread);
    }
    else
    {
        ret1 = RT_ERROR;
    }
    return ret1;
}
INIT_APP_EXPORT(ble_init);
